package demo.netty.netty.http.echo_server;

import demo.netty.util.ByteUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.StandardCharsets;

public class EchoClient {

    public static void main(String[] args) {
//        new EchoClient().bind("127.0.0.1", 8080);
        ByteBuf buffer = Unpooled.buffer(1024);
        buffer.writeByte(0x55);
        buffer.setShort(1, 47);
        buffer.writeByte(0xA0);
        buffer.writeByte(0x00);
        buffer.writeShort(0x00);
        buffer.writeShort(0x00);
        buffer.writeByte(0x02);
        buffer.writeLong(888888888L);
        byte[] bytes = {92, 79, 6, 40, 22, 10, 26, 4, 86, 89};
        System.out.println(ByteUtils.bytesToHexString(bytes));
        ByteBuf ccid = Unpooled.buffer(10);
        ccid.writeBytes(bytes);
        System.out.println(ByteUtils.bytesToHexString(ccid.slice().array()));
        buffer.writeBytes(ccid);
    }


    private void bind(String host, int port) {

        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer("@".getBytes(StandardCharsets.UTF_8));
                            //1024代表单条消息最大长度，当到达该长度的后还没有找到分隔符，就抛出TooLongFrameException异常， 使用指定分隔符进行拆分数据包
                            DelimiterBasedFrameDecoder delimiterBasedFrameDecoder = new DelimiterBasedFrameDecoder(1024, delimiter);
                            socketChannel.pipeline().addLast(delimiterBasedFrameDecoder);
                        /*//定长解码器，按照指定长度进行解码
                        socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(20));*/
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }


    }


    public static class EchoClientHandler extends SimpleChannelInboundHandler<Object> {

        private int counter;

        static final String ECHO_REQ = "Hi, Lilinfeng. Welcome to Netty. @";

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for (int i = 0; i < 20; i++) {
                ByteBuf echo = Unpooled.copiedBuffer(ECHO_REQ.getBytes(StandardCharsets.UTF_8));
                ctx.writeAndFlush(echo);
            }
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            String body = (String) msg;
            System.out.println("This is " + ++counter + " times receive client : [" + body + "]");
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }
    }


}
